package com.jn.algorithm.other.question53;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author 江南大学1033190417
 * @date 2022/5/21 17:51
 */
public class Solution {
    Deque<Integer> stack = new ArrayDeque<>();

    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        print(root, p.val);
        if (stack.peekLast() == p.val) {
            return null;
        } else {
            return new TreeNode(stack.peekLast());
        }
    }

    //中序遍历
    public void print(TreeNode root, int val) {
        if (root.left != null) {
            print(root.left, val);
        }
        if (!stack.isEmpty() && stack.peekLast() == val) {
            stack.addLast(root.val);
            return;
        }
        if (root.val == val) {
            stack.addLast(root.val);
        }
        if (root.right != null) {
            print(root.right, val);
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        TreeNode root = new TreeNode(5);
        TreeNode t1 = new TreeNode(3);
        TreeNode t2 = new TreeNode(6);
        root.left = t1;
        root.right = t2;
        TreeNode t3 = new TreeNode(2);
        TreeNode t4 = new TreeNode(4);
        t1.left = t3;
        t1.right = t4;
        t3.left = new TreeNode(1);

        TreeNode re = solution.inorderSuccessor(root, new TreeNode(1));
        System.out.println(re.val);
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}
